package com.letu.plumelog.util;

import com.alibaba.fastjson.JSONObject;
import com.letu.core.plumelog.CompressMessage;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * LZ4Util
 *
 * @author caijian
 * time 2021/1/26 6:10 下午
 */
public class LZ4Util {


    /**
     * 压缩数据
     *
     * @param messageList
     * @return
     */
    public static CompressMessage compressedMessage(List<String> messageList) {
        String text = JSONObject.toJSONString(messageList);
        byte[] textByte = text.getBytes(StandardCharsets.UTF_8);
        byte[] compressedByte = compressedByte(textByte);
        CompressMessage compressMessage = new CompressMessage();
        compressMessage.setBody(compressedByte);
        compressMessage.setLength(textByte.length);
        compressMessage.setId(UUID.randomUUID().toString());
        return compressMessage;
    }

    /**
     * 解压数据
     *
     * @param compressMessage
     * @return
     */
    public static List<String> decompressorMessage(CompressMessage compressMessage) {
        Long l =System.currentTimeMillis();
        byte[] textByte = decompressorByte(compressMessage.getBody(), compressMessage.getLength());
        String json = new String(textByte);
        List<String> list = new ArrayList<>();
        list.addAll(JSONObject.parseArray(json, String.class));
//        System.out.println("解压缩耗时：" +( System.currentTimeMillis()-l));
        return list;
    }


    /**
     * @param srcByte 原始数据
     * @return 压缩后的数据
     */
    public static byte[] compressedByte(byte[] srcByte) {
        Long l =System.currentTimeMillis();
        LZ4Factory factory = LZ4Factory.fastestInstance();
        LZ4Compressor compressor = factory.fastCompressor();
        byte[] bytes = compressor.compress(srcByte);
//        System.out.println("耗时：" +( System.currentTimeMillis()-l));
        return bytes;
    }

    /**
     * @param compressorByte 压缩后的数据
     * @param srcLength      压缩前的数据长度
     * @return byte[]
     */
    public static byte[] decompressorByte(byte[] compressorByte, int srcLength) {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        LZ4FastDecompressor decompressor = factory.fastDecompressor();
        return decompressor.decompress(compressorByte, srcLength);
    }


}
